package com.edais.service.imp.gift;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.edais.service.SystemSettingService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.edais.domain.User;
import com.edais.domain.gift.GiftPackage;
import com.edais.domain.gift.GiftPackageGift;
import com.edais.domain.gift.GiftPackageOrder;
import com.edais.persistence.gift.GiftPackageMapper;
import com.edais.persistence.gift.GiftPackageOrderMapper;
import com.edais.service.UserService;
import com.edais.service.gift.GiftPackageGiftService;
import com.edais.service.gift.GiftPackageService;
import com.edais.service.imp.GiftExchangeFunctionInvoke;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DateUtil;
import com.edais.vo.GiftPackageGiftVo;
import com.edais.vo.GiftPackageOrderVo;

/**
 * 礼包ServiceImpl
 * Created by haoyx on 2016/11/14.
 */
@Service
public class GiftPackageServiceImpl implements GiftPackageService {

    private static final Logger logger = Logger.getLogger(GiftPackageServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private GiftPackageOrderMapper orderMapper;

    @Autowired
    private GiftPackageGiftService giftPackageGiftService;

    @Autowired
    private GiftPackageMapper giftPackageMapper;

    @Autowired
    private GiftPackageOrderMapper giftPackageOrderMapper;

    @Autowired
    private GiftExchangeFunctionInvoke invoke;

    @Autowired
    private SystemSettingService systemSettingService;

    private GiftPackageOrder loadGiftPackageOrder(Long id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public GiftPackage selectByPrimaryKey(Long id) {
        return giftPackageMapper.selectByPrimaryKey(id);
    }

    private GiftPackageOrder selectGiftPackageOrder(Long id, String status) {
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("id",id);
        params.put("status",status);
        return orderMapper.selectGiftPackageOrder(params);
    }

    @Override
    public Map<String, Object> queryGiftPackageList(Map<String, String> params) throws Exception {
        Map<String, Object> resMap = new HashMap<String, Object>();
        //参数列表
        Long userId = Long.parseLong(params.get("userId"));
        String mobile = String.valueOf(params.get("mobile"));

        final String logInfo = "大礼包列表"  + userId + "-";

        String error = validQueryGiftPackageListParams(params);
        if(!StringUtils.isEmpty(error)){
            logger.info(error);
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    error,Consts.ERROR_CN);
            resMap.put("error",error);
            return resMap;
        }

        //验证用户合法性
        User user = this.userService.selectUser(userId,mobile);
        if(null == user){
            logger.info(logInfo+"查询不到此用户");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    "查询不到此用户",Consts.ERROR_CN);
            resMap.put("error",error);
            return resMap;
        }

        //获取分页参数
        int pageIndex = 1;
        int pageSize = 10;

        if(params.containsKey("pageSize")){
            pageSize = Integer.valueOf(params.get("pageSize"));
            if(pageSize > 50) pageSize = 10;
        }

        if(params.containsKey("current")){
            pageIndex = Integer.valueOf(params.get("current"));
            if(pageIndex < 0) pageSize = 1;
        }

        String packageType = String.valueOf(params.get("packageType"));

        Map<String,Object> listParam = new HashMap<String, Object>();
        listParam.put("userId",userId);
        listParam.put("current",(pageIndex -1) * pageSize);
        listParam.put("pageSize",pageSize);
        listParam.put("packageType",packageType);

        List<GiftPackageOrder> list = this.orderMapper.selectGiftPackageOrders(listParam);
        int totalNum = this.orderMapper.countGiftPackageOrders(listParam);

        //查询礼包资产
        BigDecimal gift_balance = this.orderMapper.sumGiftPackageOrders(listParam);

        resMap.put("rescode", Consts.SUCCESS_CODE);
        resMap.put("resmsg_cn", "查询成功");
        resMap.put("listSize", list.size());
        resMap.put("gift_balance", gift_balance.toString());
        resMap.put("totalNum", totalNum);
        resMap.put("list", toGiftPackageOrderVo(list));

        return resMap;
    }

    private List<GiftPackageOrderVo> toGiftPackageOrderVo(List<GiftPackageOrder> orders){
        List<GiftPackageOrderVo> result = new ArrayList<GiftPackageOrderVo>();
        for(GiftPackageOrder order : orders)
            result.add(new GiftPackageOrderVo(order));
        return result;
    }
    private String validQueryGiftPackageListParams(Map<String,String> params){
        if(null == params || params.isEmpty())
            return "参数列表不能为空";
        if(!params.containsKey("userId")  || StringUtils.isEmpty(params.get("userId")))
            return "参数userId不能为空";
        if(!params.containsKey("mobile")  || StringUtils.isEmpty(params.get("mobile")))
            return "参数mobile不能为空";
        if(!params.containsKey("packageType")  || StringUtils.isEmpty(params.get("packageType")))
            return "参数packageType不能为空";
        return null;
    }

    @Override
    public Map<String, Object> queryGiftPackageGiftList(Map<String, String> params) throws Exception {

        Map<String, Object> resMap = new HashMap<String, Object>();
        //参数列表
        Long userId = Long.parseLong(params.get("userId"));
        String mobile = String.valueOf(params.get("mobile"));

        final String logInfo = "查询礼包礼品列表"  + userId + "-";

        String error = validqueryGiftPackageGiftListParams(params);
        if(!StringUtils.isEmpty(error)){
            logger.info(error);
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,error);
            resMap.put("error",error);
            return resMap;
        }

        //验证用户合法性
        User user = this.userService.selectUser(userId,mobile);
        if(null == user){
            logger.info(logInfo+"查询不到此用户");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,"查询不到此用户");
            resMap.put("error",error);
            return resMap;
        }

        Long packageId = Long.parseLong(params.get("packageId"));
        //验证订单内的礼包合法性
        GiftPackage giftPackage = this.selectByPrimaryKey(packageId);
        if(null == giftPackage){
            logger.info(logInfo+"查询不到此礼包");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001,"查询不到此礼包");
            resMap.put("error",error);
            return resMap;
        }

        logger.info(logInfo+"开始");

        //获取分页参数
        int pageIndex = 1;
        int pageSize = 10;

        if(params.containsKey("pageSize")){
            pageSize = Integer.valueOf(params.get("pageSize"));
            if(pageSize > 50) pageSize = 10;
        }

        if(params.containsKey("current")){
            pageIndex = Integer.valueOf(params.get("current"));
            if(pageIndex < 0) pageSize = 1;
        }

        //查询礼品
        Map<String,Object> listParam = new HashMap<String, Object>();
        listParam.put("packageId",packageId);
        listParam.put("current",(pageIndex -1) * pageSize);
        listParam.put("pageSize",pageSize);
        List<GiftPackageGift> list = giftPackageGiftService.selectGiftPackageGiftPage(listParam);
        giftFomartImageUrl(list);
        int totalNum = giftPackageGiftService.countGiftPackageGiftPage(listParam);
        resMap.put("rescode", Consts.SUCCESS_CODE);
        resMap.put("resmsg_cn", "查询成功");
        resMap.put("listSize", list.size());
        resMap.put("totalNum", totalNum);
        resMap.put("list", toGiftPackageGiftVo(list));

        logger.info(logInfo+"结束");
        return resMap;
    }

    /**
     * 格式化礼品图片Url
     * @param list
     */
    @Override
    public void giftFomartImageUrl(List<GiftPackageGift> list) throws Exception {
        if(null == list || list.isEmpty())
            return;
        //查询出前缀
        String urlPrefix = this.systemSettingService.getSystemSettingValueByName(Consts.SystemSettingUpload.UPLOAD_MOBILE_VISIT_IP);
        if(StringUtils.isEmpty(urlPrefix))
            return;
        for(GiftPackageGift gift : list){
            if(StringUtils.isEmpty(gift.getGiftImageUrl()))
                continue;
            gift.setGiftImageUrl(urlPrefix + gift.getGiftImageUrl());
        }
    }

    private String validqueryGiftPackageGiftListParams(Map<String,String> params){
        if(null == params || params.isEmpty())
            return "参数列表不能为空";
        if(!params.containsKey("userId")  || StringUtils.isEmpty(params.get("userId")))
            return "参数userId不能为空";
        if(!params.containsKey("mobile")  || StringUtils.isEmpty(params.get("mobile")))
            return "参数mobile不能为空";
        if(!params.containsKey("packageId")  || StringUtils.isEmpty(params.get("packageId")))
            return "参数packageId不能为空";
        return null;
    }

    private List<GiftPackageGiftVo> toGiftPackageGiftVo(List<GiftPackageGift> gifts){
        List<GiftPackageGiftVo> result = new ArrayList<GiftPackageGiftVo>();
        for(GiftPackageGift gift : gifts)
            result.add(new GiftPackageGiftVo(gift));
        return result;
    }

    @Override
//    @Async
    public Map<String, String> giveWelFarePackage(Map<String, String> params) throws Exception {

        Map<String, String> resMap = new HashMap<String, String>();
        String error = validGivePackageParams(params);
        if(!StringUtils.isEmpty(error)){
            logger.info(error);
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE,
                    error,Consts.ERROR_CN);
            resMap.put("error",error);
            return resMap;
        }

        //参数列表
        Long userId = Long.parseLong(params.get("userId"));
        String mobile = String.valueOf(params.get("mobile"));
        Long packageId = Long.parseLong(params.get("packageId"));

        final String logInfo = "赠送礼包" + packageId + userId + "-";

        //验证用户合法性
        User user = this.userService.selectUser(userId,mobile);
        if(null == user){
            logger.info(logInfo+"查询不到此用户");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    "查询不到此用户",Consts.ERROR_CN);
            resMap.put("error",error);
            return resMap;
        }

        Date nowDate = this.userService.getSysdate();

        logger.info(logInfo+"开始");

        //验证礼包
        GiftPackage giftPackage = this.selectByPrimaryKey(packageId);
        if(null == giftPackage){
            logger.info(logInfo+"查询不到此礼包");
            error = CommonUtil.setResultStringCn(new HashMap<String, Object>(),Consts.ERROR_CODE,
                    "查询不到此礼包",Consts.ERROR_CN);
            resMap.put("error",error);
            return resMap;
        }

        this.generateWelFareOrder(logInfo,user, giftPackage,nowDate);

        logger.info(logInfo+"结束");

        return resMap;
    }

    private String validGivePackageParams(Map params) {
        if(null == params || params.isEmpty())
            return "参数列表不能为空";
        if(!params.containsKey("userId")  || StringUtils.isEmpty(params.get("userId")))
            return "参数userId不能为空";
        if(!params.containsKey("mobile")  || StringUtils.isEmpty(params.get("mobile")))
            return "参数mobile不能为空";
        if(!params.containsKey("packageId")  || StringUtils.isEmpty(params.get("packageId")))
            return "参数packageId不能为空";
        return null;
    }

    /**
     * 生成订单礼包
     * @param logInfo               日志头
     * @param user                      用户
     * @param giftPackage       礼包
     * @param nowDate           当前数据库时间
     * @return                          礼包订单
     */
    private GiftPackageOrder generateWelFareOrder(String logInfo, User user, GiftPackage giftPackage, Date nowDate){
        String nowLogInfo = logInfo + "生成订单";
        logger.info(nowLogInfo + "开始");
        GiftPackageOrder order = new GiftPackageOrder();
        order.setUrl(giftPackage.getUrl());
        order.setContent(giftPackage.getContent());
        order.setUserId(Long.valueOf(user.getId()));
        order.setUserName(user.getNick_name());
        order.setUserMobile(user.getMobile());
        order.setPackageId(giftPackage.getId());
        order.setPackageName(giftPackage.getName());
        order.setPackageContent(giftPackage.getContent());
        order.setStartDate(DateUtil.getExpiryDate(nowDate,giftPackage.getStartDate()));
        order.setEndDate(DateUtil.getExpiryDate(nowDate,giftPackage.getEndDate()));
        order.setPackageExchangeServiceName(giftPackage.getExchangeServiceName());
        order.setPackageExchangeServiceParam(giftPackage.getExchangeServiceParam());
        order.setName(giftPackage.getName());
        order.setCreatePer("javaservice");
        order.setCreateTime(nowDate);
        order.setPackageType(giftPackage.getType());
        order.setPackageTypeName(giftPackage.getTypeName());
        order.setStatus(GiftPackageOrder.STATUS_INIT);
        this.giftPackageOrderMapper.insert(order);
        logger.info(nowLogInfo + "成功");
        return order;
    }
}
